if(jQuery) (function($){
	
	$.extend($.fn, {
		layout: function(panels, o) {
			// Defaults
			if( !o ) var o = {};
			if( o.container == undefined ) o.container = window;
			if( o.innerSpacing == undefined ) o.innerSpacing = 0;
			if( o.offsetTop == undefined ) o.offsetTop =0;
			if( o.offsetLeft == undefined ) o.offsetLeft= 0;
			if( o.offsetBottom == undefined ) o.offsetBottom = 0;
			if( o.offsetRight == undefined ) o.offsetRight = 0;
			if( o.autoResize == undefined ) o.autoResize = false;
			
			$(this).each( function() {

				function resize() {
					var containerWidth = $(o.container).width() - o.offsetLeft - o.offsetRight;
					var containerHeight = $(o.container).height() - o.offsetTop - o.offsetBottom;

					var currentY = o.offsetTop;
					for (var r=0; r < panels.length; ++r) {
						var currentX = o.offsetLeft;
						var panelTopHeight = 0;
		
						for (var c=0; c < panels[r].length; ++c) {
							var panel = panels[r][c];
							var panelWidth;



							if (panel.width == 'fill') {
								panelWidth = containerWidth - panelData.totalX[r];
							} else {
								panelWidth = panel.width;
							}
							
							
							// Panel Padding
							if(typeof panel.padWidth == 'undefined') {
								panel.padWidth = 0;
							}

							$(panel.id).css('width',  panelWidth+panel.padWidth);
							$(panel.id).css('left', currentX);

							currentX += panelWidth;
							if (c != panels[r].length - 1) {
								currentX += o.innerSpacing;
							}


							if (panel.height == 'fill') {
								panelHeight = containerHeight - panelData.totalY;
							} else {
								panelHeight = panel.height;
							}
							
							// Panel Padding
							if(typeof panel.padHeight == 'undefined') {
								panel.padHeight = 0;
							}

							$(panel.id).css('height', panelHeight+panel.padHeight);
							$(panel.id).css('top', currentY);

							panelTopHeight = Math.max(panelTopHeight, panelHeight);
						}

						currentY += panelTopHeight;
						if (r != panels.length - 1) {
							currentY += o.innerSpacing;
						}
					}
				}


				var panelData = {};

				panelData.totalX = [];
				panelData.totalY = 0;

				for (var r=0; r < panels.length; ++r) {
					for (var c=0; c < panels[r].length; ++c) {
						var panel = panels[r][c];

						$(panel.id).css('position', 'absolute');
		
						if (typeof panelData.totalX[r] == 'undefined') {
							panelData.totalX[r] = 0;
						}
		
						if (panel.height != 'fill') {
							panelData.totalY += panel.height;
						}
						if (panel.width != 'fill') {
							panelData.totalX[r] += panel.width;
						}
					}
					panelData.totalX[r] += (panels[r].length - 1) * o.innerSpacing;
				}
				panelData.totalY += (panels.length - 1) * o.innerSpacing;

				resize();
				if (o.autoResize)
					window.onresize = function(){resize();}
			});
		}
	});
	
})(jQuery);

